from utils.my_drf.viewsets import CustomModelViewSet
from utils.my_drf.admin_auth import AdminJwtAuth, AdminPermission
from rest_framework.filters import SearchFilter
from django_filters.rest_framework import DjangoFilterBackend
from . import models, serializer
from utils.my_drf.pagination import CommonPageNumberPagination
from record.models import AdminRecord


class AdminArticleView(CustomModelViewSet):
    authentication_classes = [AdminJwtAuth, ]
    permission_classes = [AdminPermission, ]
    filter_backends = [SearchFilter, DjangoFilterBackend]
    search_fields = ['title']
    filterset_fields = ['sort', 'admin']
    queryset = models.Article.objects.filter(is_delete=False).order_by('-id')
    serializer_class = serializer.AdminArticleSerializer
    pagination_class = CommonPageNumberPagination

    def get_serializer_class(self):
        if self.request.method == 'GET' and self.request.path == '/api/article/backstage/':
            return serializer.ArticleListSerializer
        return self.serializer_class

    def create(self, request, *args, **kwargs):
        res = super().create(request, *args, **kwargs)
        AdminRecord.objects.create(group=2, detail='添加文章，内容：{}'.format(str(res.data.get('data'))),
                                   admin_id=request.user.get('id'))
        return res

    def update(self, request, *args, **kwargs):
        res = super().update(request, *args, **kwargs)
        AdminRecord.objects.create(group=2, detail='修改文章，内容：{}'.format(str(res.data.get('data'))),
                                   admin_id=request.user.get('id'))
        return res

    def destroy(self, request, *args, **kwargs):
        res = super().destroy(request, *args, **kwargs)
        AdminRecord.objects.create(group=2, detail='删除文章，id：{}'.format(str(res.data.get('data'))),
                                   admin_id=request.user.get('id'))
        return res
